package com.cryptape.cita_wallet.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.MapUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cryptape.cita_wallet.CytonApplication;
import com.cryptape.cita_wallet.activity.AddWalletActivity;
import com.cryptape.cita_wallet.activity.CurrencyActivity;
import com.cryptape.cita_wallet.activity.MainActivity;
import com.cryptape.cita_wallet.activity.MyInvitationCodeActivity;
import com.cryptape.cita_wallet.activity.SimpleWebActivity;
import com.cryptape.cita_wallet.activity.SwitchLanguageActivity;
import com.cryptape.cita_wallet.activity.WalletManageActivity;
import com.cryptape.cita_wallet.activity.bindwallet.BindMGPWalletActivity;
import com.cryptape.cita_wallet.activity.changewallet.ChangeWalletActivity;
import com.cryptape.cita_wallet.activity.cloudminer.CloudMinerActivity;
import com.cryptape.cita_wallet.activity.cloudminer.MinerIncomeActivity;
import com.cryptape.cita_wallet.activity.transfer.TransferActivity;
import com.cryptape.cita_wallet.constant.ConstantUtil;
import com.cryptape.cita_wallet.constant.url.HttpUrls;
import com.cryptape.cita_wallet.item.Token;
import com.cryptape.cita_wallet.item.Wallet;
import com.cryptape.cita_wallet.net.callback.CommonCallback;
import com.cryptape.cita_wallet.net.request.HttpRequestMode;
import com.cryptape.cita_wallet.net.response.BaseResponse;
import com.cryptape.cita_wallet.service.http.EthRpcService;
import com.cryptape.cita_wallet.util.Blockies;
import com.cryptape.cita_wallet.util.RSAUtils;
import com.cryptape.cita_wallet.util.db.DBWalletUtil;
import com.cryptape.cita_wallet.util.db.SharePrefUtil;
import com.cryptape.cita_wallet.util.fingerprint.AuthenticateResultCallback;
import com.cryptape.cita_wallet.util.fingerprint.FingerPrintController;
import com.cryptape.cita_wallet.view.SettingButtonView;
import com.cryptape.cita_wallet.view.dialog.AuthFingerDialog;
import com.cryptape.cita_wallet.view.dialog.SimpleDialog;
import com.cryptape.cita_wallet.view.dialog.SimpleSelectDialog;
import com.cryptape.cita_wallet.view.dialog.ToastSingleButtonDialog;
import com.mangoworld.android.R;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

;

/**
 * Created by duanyytop on 2018/4/17
 */
public class SettingsFragment extends NBaseFragment {

    private static final int Currency_Code = 10001;
    public static final String TAG = SettingsFragment.class.getName();
    private SettingButtonView mSbvCurrency, sbv_manager_wallet, mSbvSelectLanguage,
            mSbvFingerPrint, mSbvForums, mSbvSelectEth, mMyVStimulate, mSbvBindMGPWallet;
    public static SettingButtonView mMyInvitationCode;
    private TextView walletNameText, walletAddressText;
    private CircleImageView photoImage;
    private RelativeLayout walletLayout;
    private AuthFingerDialog mAuthFingerDialog = null;
    private List<String> ethNodeList = Arrays.asList(ConstantUtil.ETH_NET_MAIN, ConstantUtil.ETH_NET_ROPSTEN_TEST
            , ConstantUtil.ETH_NET_KOVAN_TEST, ConstantUtil.ETH_NET_RINKEBY_TEST);
    private int ethNodeIndex;
    private FingerPrintController mFingerPrintController;
    private TextView tv_version;
    private SwipeRefreshLayout swipeRefreshLayout;
    private int bindCode = 2;

    /**
     * 定义一个变量来进行计数
     */
    private int i = 0;

    private boolean testModeFlag = true;

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_settings;
    }

    @Override
    public void initView() {
        mMyVStimulate = (SettingButtonView) findViewById(R.id.sbv_my_v_stimulate);
        mMyInvitationCode = (SettingButtonView) findViewById(R.id.sbv_my_invitationcode);
        mSbvCurrency = (SettingButtonView) findViewById(R.id.sbv_local_coin);
        sbv_manager_wallet = (SettingButtonView) findViewById(R.id.sbv_manager_wallet);
        mSbvSelectLanguage = (SettingButtonView) findViewById(R.id.sbv_select_language);
        mSbvFingerPrint = (SettingButtonView) findViewById(R.id.sbv_fingerprint);
        mSbvForums = (SettingButtonView) findViewById(R.id.sbv_forums);
        mSbvSelectEth = (SettingButtonView) findViewById(R.id.sbv_eth_select);
        walletNameText = (TextView) findViewById(R.id.text_wallet_name);
        walletAddressText = (TextView) findViewById(R.id.text_wallet_address);
        walletLayout = (RelativeLayout) findViewById(R.id.wallet_information_layout);
        photoImage = (CircleImageView) findViewById(R.id.wallet_photo);
        tv_version = (TextView) findViewById(R.id.tv_version);
        mSbvBindMGPWallet = (SettingButtonView) findViewById(R.id.sbv_bind_mgp_wallet);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        (findViewById(R.id.tv_change_mode_down)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!testModeFlag) {
                    i++;
                    testModeFlag = true;
                }
            }
        });
        boolean isEnabled = false;
        tv_version.setEnabled(isEnabled);
        tv_version.setClickable(isEnabled);
        tv_version.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (testModeFlag) {
                    i++;
                    testModeFlag = false;
                }
                if (i == 3) {
                    String mode;
                    if (ConstantUtil.isTestMode) {
                        //如果为测试模式,保存值为false，下次启动app就是正式模式
                        mode = getResources().getString(R.string.str_current_mode_is_test_will_switch_formal);
                    } else {
                        //如果为正式模式,保存值为true，下次启动app就是测试模式
                        mode = getResources().getString(R.string.str_current_mode_is_formal_will_switch_test);
                    }
                    showChangeModeDialog(mode, !ConstantUtil.isTestMode);
                }
            }
        });

        if (ObjectUtils.isEmpty(CytonApplication.getInstance().MIDCode)) {
            mMyInvitationCode.setVisibility(View.GONE);
        } else {
            mMyInvitationCode.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void initData() {
        Wallet wallet = DBWalletUtil.getCurrentWallet(getContext());
        if (wallet == null) {
            return;
        }
        walletNameText.setText(wallet.name);
        walletAddressText.setText(wallet.address);
        photoImage.setImageBitmap(Blockies.createIcon(wallet.address));

        updateEthNode();

        mFingerPrintController = new FingerPrintController(getActivity());
        mSbvCurrency.setRightText(SharePrefUtil.getString(ConstantUtil.CURRENCY, ConstantUtil.DEFAULT_CURRENCY));
//        if (mFingerPrintController.isSupportFingerprint()) {
//            mSbvFingerPrint.setVisibility(View.VISIBLE);
//            if (SharePrefUtil.getBoolean(ConstantUtil.FINGERPRINT, false)) {
//                mSbvFingerPrint.setSwitchCheck(true);
//            } else {
//                SharePrefUtil.putBoolean(ConstantUtil.FINGERPRINT, false);
//                mSbvFingerPrint.setSwitchCheck(false);
//            }
//        } else
        {
            mSbvFingerPrint.setVisibility(View.GONE);
        }
        String node = SharePrefUtil.getString(ConstantUtil.ETH_NET, ConstantUtil.ETH_MAINNET);
        if (node.contains("_")) node = node.replace("_", " ");
        mSbvSelectEth.setRightText(node);

        try {
            String versionName = getContext().getPackageManager()
                    .getPackageInfo(getContext().getPackageName(), 0).versionName;
            tv_version.setText(String.format("Version V%s", versionName));
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        refresh();
    }

    @Override
    public void initAction() {
        mMyVStimulate.setOnClickListener(() -> {
            Intent intent = new Intent(getActivity(), MinerIncomeActivity.class);
            intent.putExtra("isVStimulate", true);
            startActivity(intent);
        });
        mMyInvitationCode.setOnClickListener(() -> {
            Intent intent = new Intent(getActivity(), MyInvitationCodeActivity.class);
            startActivity(intent);
        });
        mSbvCurrency.setOnClickListener(() -> {
            Intent intent = new Intent(getActivity(), CurrencyActivity.class);
            startActivityForResult(intent, Currency_Code);
        });
        mSbvFingerPrint.setSwitchCheckedListener(isChecked -> {
            if (isChecked) {
                //setting fingerprint
                if (mFingerPrintController.hasEnrolledFingerprints() && mFingerPrintController.getEnrolledFingerprints().size() > 0) {
                    if (mAuthFingerDialog == null)
                        mAuthFingerDialog = new AuthFingerDialog(getActivity());
                    mAuthFingerDialog.setOnShowListener((dialogInterface) -> {
                        mFingerPrintController.authenticate(authenticateResultCallback);
                    });
                    mAuthFingerDialog.setOnDismissListener((dialog) -> {
                        mFingerPrintController.cancelAuth();
                    });
                    mAuthFingerDialog.show();
                } else {
                    ToastSingleButtonDialog dialog = ToastSingleButtonDialog.getInstance(
                            getActivity(), getResources().getString(R.string.dialog_finger_setting));
                    dialog.setOnCancelClickListener(view -> {
                        FingerPrintController.openFingerPrintSettingPage(getActivity());
                        view.dismiss();
                    });
                }
            } else {
                //close fingerprint
                SharePrefUtil.putBoolean(ConstantUtil.FINGERPRINT, false);
                mSbvFingerPrint.setSwitchCheck(false);
            }
        });
        sbv_manager_wallet.setOnClickListener(() -> {
            if (DBWalletUtil.getAllWallet(getActivity()).size() >= 1) {
                startActivity(new Intent(getActivity(), ChangeWalletActivity.class));
                getActivity().overridePendingTransition(R.anim.wallet_activity_in, 0);
            } else {
                getActivity().startActivity(new Intent(getActivity(), AddWalletActivity.class));
            }
        });
        mSbvSelectLanguage.setOnClickListener(() -> {
            startActivity(new Intent(getContext(), SwitchLanguageActivity.class));
//
//            ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
//            ClipData mClipData = ClipData.newPlainText("contact", "Nervos-Neuron");
//            if (cm != null) {
//                cm.setPrimaryClip(mClipData);
//                Toast.makeText(getActivity(), R.string.copy_weixin_success, Toast.LENGTH_SHORT).show();
//            }
        });
        mSbvForums.setOnClickListener(() -> {
            SimpleWebActivity.gotoSimpleWeb(getActivity(), HttpUrls.CITAHUB_TALK_URL);
        });
        mSbvSelectEth.setOnClickListener(() -> {
            SimpleSelectDialog dialog = new SimpleSelectDialog(getActivity(), ethNodeList, -1);
            dialog.setMSelected(ethNodeIndex);
            dialog.setOnOkListener((view -> {
                ethNodeIndex = dialog.getMSelected();
                SharePrefUtil.putString(ConstantUtil.ETH_NET, ethNodeList.get(ethNodeIndex));
                MainActivity.updateContract();
                dialog.dismiss();
            }));
            dialog.setOnDismissListener(dialogInterface -> {
                EthRpcService.initNodeUrl();
                updateEthNode();
                String node = SharePrefUtil.getString(ConstantUtil.ETH_NET, ConstantUtil.ETH_NET_MAIN);
                if (node.contains("_")) node = node.replace("_", " ");
                mSbvSelectEth.setRightText(node);
                MainActivity.updateContract();
                dialog.dismiss();
            });
        });
        walletLayout.setOnClickListener(v ->
                startActivity(new Intent(getContext(), WalletManageActivity.class)));
//        mSbvSelectLanguage.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(getContext(), SwitchLanguageActivity.class));
//            }
//        });


        mSbvBindMGPWallet.setOnClickListener(() -> {
            //备注: 0绑定成功 1绑定中 2 需绑定 3 错误信息(直接弹出)  5暂未开启
            if (bindCode == 0 || bindCode == 2) {
                Token token = new Token(ConstantUtil.ETH_MAINNET, ConstantUtil.ETH, ConstantUtil.ETHEREUM_MAIN_ID);
                if (bindCode == 2) {
                    token = new Token(ConstantUtil.ETH, ConstantUtil.ETH, 18, null, ConstantUtil.ETHEREUM_MAIN_ID);
                } else if (bindCode == 0) {
                    token = new Token(ConstantUtil.getDefaultCoin(), ConstantUtil.getDefaultCoin(), 18, null, ConstantUtil.MGP_CHAIN_ID);
                }
                Intent intent = new Intent(getActivity(), BindMGPWalletActivity.class);
                intent.putExtra(BindMGPWalletActivity.EXTRA_TOKEN, token);
                intent.putExtra("bindCode", bindCode);
                startActivity(intent);
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private void updateEthNode() {
        switch (SharePrefUtil.getString(ConstantUtil.ETH_NET, ConstantUtil.ETH_NET_MAIN)) {
            case ConstantUtil.ETH_NET_MAIN:
            default:
                ethNodeIndex = 0;
                break;
            case ConstantUtil.ETH_NET_ROPSTEN_TEST:
                ethNodeIndex = 1;
                break;
            case ConstantUtil.ETH_NET_KOVAN_TEST:
                ethNodeIndex = 2;
                break;
            case ConstantUtil.ETH_NET_RINKEBY_TEST:
                ethNodeIndex = 3;
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
        LogUtils.dTag("isVisibleToUser", "mMyInvitationCode onResume MIDCode = " + CytonApplication.getInstance().MIDCode);
        if (ObjectUtils.isEmpty(CytonApplication.getInstance().MIDCode)) {
            mMyInvitationCode.setVisibility(View.GONE);
        } else {
            mMyInvitationCode.setVisibility(View.VISIBLE);
        }
    }

    AuthenticateResultCallback authenticateResultCallback = new AuthenticateResultCallback() {
        @Override
        public void onAuthenticationError(String errorMsg) {
            mSbvFingerPrint.setSwitchCheck(false);
            Toast.makeText(getContext(), errorMsg, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onAuthenticationSucceeded() {
            mSbvFingerPrint.setSwitchCheck(true);
            if (mAuthFingerDialog != null && mAuthFingerDialog.isShowing())
                mAuthFingerDialog.dismiss();
            SharePrefUtil.putBoolean(ConstantUtil.FINGERPRINT, true);
            Toast.makeText(getContext(), getResources().getString(R.string.fingerprint_setting_sucess), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onAuthenticationFailed() {
            mSbvFingerPrint.setSwitchCheck(false);
            Toast.makeText(getContext(), getResources().getString(R.string.fingerprint_setting_failed), Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case Currency_Code:
                    mSbvCurrency.setRightText(SharePrefUtil.getString(ConstantUtil.CURRENCY, "CNY"));
                    break;
            }
        }
    }

    /**
     * @param mode       当前模式
     * @param isTestMode 是否测试模式
     */
    private void showChangeModeDialog(String mode, final boolean isTestMode) {
        AlertDialog.Builder builder;
        builder = new AlertDialog.Builder(getActivity()).setTitle(getResources().getString(R.string.str_mode_switch))
                .setMessage(mode).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int fag) {
                        SPUtils.getInstance(ConstantUtil.MANGO_WORLD_PREFERENCE_OTHER_INFO).put(ConstantUtil.SP_FIRSTSTARTAPP, true);
                        //将是否是测试或者正式模式的boolean值保存下来
                        SPUtils.getInstance(ConstantUtil.MANGO_WORLD_PREFERENCE_OTHER_INFO).put(ConstantUtil.SP_MODE_CHANGE, isTestMode);
                        dialogInterface.dismiss();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                AppUtils.relaunchApp();
                            }
                        }, 3000);
                    }
                }).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int fag) {
                        //初始化标识的值
                        i = 0;
                        testModeFlag = true;
                        dialogInterface.dismiss();
                    }
                });
        builder.setCancelable(false);
        builder.create().show();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        LogUtils.dTag("isVisibleToUser", "mMyInvitationCode onHiddenChanged MIDCode = " + CytonApplication.getInstance().MIDCode);

        if (!hidden) {
            if (ObjectUtils.isEmpty(CytonApplication.getInstance().MIDCode)) {
                mMyInvitationCode.setVisibility(View.GONE);
            } else {
                mMyInvitationCode.setVisibility(View.VISIBLE);
            }
        }
    }

    public void refresh() {
        checkBind();
    }

    public void checkBind() {
        String address = DBWalletUtil.getCurrentWallet(CytonApplication.getInstance()).address;
        try {
            Map params = MapUtils.newHashMap();
            params.put("currentAddr", address);
            params.put("type", "1");
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            HttpRequestMode.checkBind(getActivity(), content, true, new CommonCallback() {
                @Override
                public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                    if (data != null) {
                        //explain: 状态码说明: 0已绑定并且转了MGP 1绑定中 2需要绑定 3系统错误判断 4已绑定但未转MGP
                        BaseResponse baseResponse = (BaseResponse) data;
                        bindCode = baseResponse.getResult();
                        if (bindCode == 3) {
                            ToastUtils.showLong(baseResponse.getMessage());
                        } else if (bindCode == 5) {
                            mSbvBindMGPWallet.setVisibility(View.GONE);
                        }
                        mSbvBindMGPWallet.setRightText(baseResponse.getMessage());
                    }
                }

                @Override
                public void onFailure(String msg, int responseFailCode) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
